/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.Forward;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.widget.BottomDialog;

import java.util.ArrayList;
import java.util.List;

public class LocationMapActivity extends BaseActivity implements AMapLocationListener, AMap.OnMyLocationChangeListener, AMap.OnCameraChangeListener, GeocodeSearch.OnGeocodeSearchListener {

    private static final String TAG = "TopicLocationMapActivit";
    private MapView mMapView = null;
    private AMapLocationClient mlocationClient;
    private MyTitleBar titleBar;
    private ProgressDialog progressDialog;
    private AMap aMap;
    private AMapLocation lastLocation;
    private Marker screenMarker;
    private double latitude;
    private double longitude;
    private LatLng latLng;
    private GeocodeSearch geocodeSearch;
    private TextView tv_address;
    private String simpleAddress;
    private Topic topic;
    private Forward forward;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //initialize SDK with context, should call this before setContentView

        setContentView(R.layout.ease_activity_baidumap);
        mMapView = findViewById(R.id.a_map_view);
        tv_address = findViewById(R.id.tv_address);
        mMapView.onCreate(savedInstanceState);
        initTitleBar();
        Intent intent = getIntent();
        topic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        forward = intent.getParcelableExtra(Constant.EXTRA_INFO_FORWARD);

        aMap = mMapView.getMap();
        mMapView.getMap();
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                if (topic != null) {
                    addMarkerInScreenCenter(topic);
                } else if (forward != null) {
                    createUserLocationMaker(forward);
                }

            }
        });
        initMapView();
        initInfoWindow();
    }

    void initTitleBar() {
        titleBar = findViewById(R.id.title_bar);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                mlocationClient.stopLocation();
                lastLocation = amapLocation;
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                LatLng latLng = new LatLng(amapLocation.getLatitude(), amapLocation.getLatitude());
                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        latLng, 18, 30, 30));
                aMap.moveCamera(cameraUpdate);

                aMap.addMarker(new MarkerOptions().position(latLng)
                        .icon(BitmapDescriptorFactory
                                .defaultMarker(BitmapDescriptorFactory.HUE_RED)));


            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

    private void location(LatLng latLng) {
        getAddressByLatLng(latLng);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                latLng, 18, 30, 30));
        aMap.moveCamera(cameraUpdate);
//        mBaiduMap.addMarker(new MarkerOptions().position(latLng)
//                .icon(BitmapDescriptorFactory
//                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
    }

    private void showMapWithLocationClient() {
        String str1 = getResources().getString(R.string.Making_sure_your_location);
        progressDialog = new ProgressDialog(this);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(str1);

        progressDialog.setOnCancelListener(new OnCancelListener() {

            public void onCancel(DialogInterface arg0) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                Log.d("map", "cancel retrieve location");
                finish();
            }
        });

        progressDialog.show();

        mlocationClient = new AMapLocationClient(this);
        mlocationClient.setLocationListener(this);
        //声明mLocationOption对象
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
    }


    private void initLocation() {


        aMap = mMapView.getMap();
        UiSettings mUiSettings = aMap.getUiSettings();

        //设置不显示指南针
        mUiSettings.setCompassEnabled(false);
        //显示定位按键
        mUiSettings.setMyLocationButtonEnabled(true);
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);// LOCATION_TYPE_LOCATE:定位一次 ，地图移动到定位地点 LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER:连续定位，图标转动，

        myLocationStyle.showMyLocation(false);
        myLocationStyle.anchor(0.5f, 0.5f);
        // myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.compass));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.strokeWidth(1f);
        myLocationStyle.interval(5000);//连续定位模式下的定位间隔时间
        aMap.setMyLocationStyle(myLocationStyle);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);

        //设置缩放级别
        aMap.animateCamera(CameraUpdateFactory.zoomTo(17));
        //设置地图倾斜度

        aMap.animateCamera(CameraUpdateFactory.changeTilt(30));

        aMap.setOnMyLocationChangeListener(this);
        aMap.setOnCameraChangeListener(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onPause() {
        mMapView.onPause();

        super.onPause();

    }

    @Override
    protected void onResume() {
        mMapView.onResume();

        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mlocationClient != null)
            mlocationClient.onDestroy();
        mMapView.onDestroy();

        super.onDestroy();
    }

    private void initMapView() {
        mMapView.setLongClickable(true);
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        initLocation();
    }

    public void createUserLocationMaker(Forward forward) {
        User targetUser = forward.getTargetUser();
        if (targetUser == null) {
            return;
        }
        double latitude = forward.getLocation().getLatitude();
        double longitude = forward.getLocation().getLongitude();
        final LatLng latLng;
        if (latitude != 0 && longitude != 0) {
            latLng = new LatLng(latitude, longitude);
        } else {
            latLng = aMap.getCameraPosition().target;
        }


        MarkerOptions markerOptions = new MarkerOptions()
                .position(latLng)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                .zIndex(0)
                .draggable(false);

        Marker mMarker = aMap.addMarker(markerOptions);
        mMarker.setObject(targetUser);
        mMarker.showInfoWindow();
        location(latLng);
    }

    /**
     * 在屏幕中心添加一个Marker
     */
    private void addMarkerInScreenCenter(Topic topic) {
        LatLng latLng;
        double latitude = topic.getLocation().getLatitude();
        double longitude = topic.getLocation().getLongitude();
        if (latitude != 0 && longitude != 0) {
            latLng = new LatLng(latitude, longitude);
        } else {
            latLng = aMap.getCameraPosition().target;
        }

        MarkerOptions markerOption = new MarkerOptions()
                .position(latLng)
                .title(topic.getTitle())
                .snippet(topic.getContent());


        markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

        final Marker maker = aMap.addMarker(markerOption);
        maker.setObject(topic);


        maker.showInfoWindow();
        location(latLng);
    }

    private void initInfoWindow() {
        aMap.setInfoWindowAdapter(new AMap.ImageInfoWindowAdapter() {
            @Override
            public long getInfoWindowUpdateTime() {
                return 0;
            }

            @Override
            public View getInfoWindow(Marker marker) {
                if (marker.getObject() instanceof Topic) {
                    Topic topic = (Topic) marker.getObject();
                    View view = LayoutInflater.from(LocationMapActivity.this).inflate(R.layout.topic_infowindow_layout_1, null);
                    TextView tv_title = view.findViewById(R.id.tv_title);
                    ImageView iv_topicType = view.findViewById(R.id.iv_topic_type);
                    ImageView iv_navigation = view.findViewById(R.id.btn_navigation);
                    tv_title.setText(topic.getTitle());
//                    RelativeLayout.LayoutParams params=new
//                    tv_title.setLayoutParams();
                    // tv_content.setText(topic.getContent());

                    if (topic.getType() != null) {

                        switch (topic.getType()) {
                            case Constant.TOPIC_TYPE_LOST_PEOPLE:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_lost_person);
                                break;
                            case Constant.TOPIC_TYPE_REWARD:
                                iv_topicType.setImageResource(R.drawable.tx_reward_coin);
                                break;
                            case Constant.TOPIC_TYPE_EXPOSE:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_expose_3);
                                break;
                            case Constant.TOPIC_TYPE_FOUND:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_found);
                                break;
                            case Constant.TOPIC_TYPE_GIFT:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_gift);
                                break;
                            case Constant.TOPIC_TYPE_AUCTION:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_auction);
                                break;
                            case Constant.TOPIC_TYPE_GOODS:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_goods);
                                break;
                            case Constant.TOPIC_TYPE_SHOW:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_show);
                                break;

                            case Constant.TOPIC_TYPE_AREA:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_area);
                                break;

                            case Constant.TOPIC_TYPE_INDUSTRY:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_industry);
                                break;

                            case Constant.TOPIC_TYPE_SCHOOL:
                                iv_topicType.setImageResource(R.drawable.tx_topic_type_school);
                                break;

                            default:
                                iv_topicType.setVisibility(View.GONE);

                        }
                    }
                    // InfoWindowView infoWindowView = new InfoWindowView(getContext(), searchResultList.get(position));
                    iv_navigation.setOnClickListener(v -> showSelectNaviDialog(topic.getLocation().getLongitude(), topic.getLocation().getLatitude(), topic.getAddress()));

                    return view;
                } else if (marker.getObject() instanceof User) {

                    User targetUser = (User) marker.getObject();

                    return generateUserLocationView(targetUser);

                }
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });


        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                startActivity(new Intent(LocationMapActivity.this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, (Topic) marker.getObject()));

                return true;
            }
        });
        aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                startActivity(new Intent(LocationMapActivity.this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, (Topic) marker.getObject()));

            }
        });
    }

    private View generateUserLocationView(User targetUser) {
        View viewInfoWindow = LayoutInflater.from(this).inflate(R.layout.baidu_maker_infowindow, null);
        viewInfoWindow.getBackground().setAlpha(175);
        TextView tv_name = viewInfoWindow.findViewById(R.id.tv_name);
        TextView tv_address = viewInfoWindow.findViewById(R.id.tv_address);
        TextView tv_time = viewInfoWindow.findViewById(R.id.tv_time);
        View btn_chat = viewInfoWindow.findViewById(R.id.btn_chat);
        ImageView iv_avatar = viewInfoWindow.findViewById(R.id.iv_avatar);
        ImageView iv_navigation = viewInfoWindow.findViewById(R.id.btn_navigation);
        if (targetUser != null) {
            // Glide.with(this).load(targetUser.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar_1).into(iv_avatar);
            GlideLoadUtils.glideLoad(this, targetUser.getAvatar(), iv_avatar, R.drawable.tx_default_avatar_1);
            tv_name.setText(targetUser.getUsername());
            tv_address.setText(targetUser.getArea());
            tv_time.setText(DateUtils.getTimestampString(targetUser.getCreated()));
            btn_chat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(LocationMapActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
                }
            });
            iv_navigation.setOnClickListener(v -> showSelectNaviDialog(targetUser.getLatLng().getLongitude(), targetUser.getLatLng().getLatitude(), targetUser.getArea()));
        }
        return viewInfoWindow;
    }

    private void showSelectNaviDialog(double longitude, double latitude, String address) {

        List<String> mapApk = getMapApk();
        if (mapApk.size() == 0) {
            showToast("在您手机上暂未找到导航软件...");
            return;
        }
        BottomDialog bottomDialog = new BottomDialog(this, mapApk, new BottomDialog.InteractionListener() {
            @Override
            public void onDialogItemViewClick(int position, String itemName) {
                Intent intent;
                switch (itemName) {
                    case "高德地图":

//
//                        intent = new Intent("androidamap://route?sourceApplication=" + getResources().getString(R.string.app_name) + "&sname=我的位置&dlat="
//                                + latitude + "&dlon=" + longitude + "&dname=" + "标题" + "&dev=1&m=2&t=3");
//                        startActivity(intent);
                        String uriString = null;
                        StringBuilder builder = new StringBuilder("amapuri://route/plan?sourceApplication=" + getResources().getString(R.string.app_name));
                        builder.append("&dlat=").append(latitude)
                                .append("&dlon=").append(longitude)
                                .append("&dname=").append(address)
                                .append("&dev=0")
                                .append("&t=0");
                        uriString = builder.toString();
                        intent = new Intent(Intent.ACTION_VIEW);
                        intent.setPackage("com.autonavi.minimap");
                        intent.setData(Uri.parse(uriString));
                        startActivity(intent);

                        break;

                    case "百度地图":
                        intent = new Intent();
                        // double[] doubles = gaoDeToBaidu(latitude, longitude);
                        intent.setData(Uri.parse("baidumap://map/direction?coord_type=gcj02&destination=" + latitude + "," + longitude + "&mode=driving"));
                        startActivity(intent);

                        break;

                    case "腾讯地图":
//                        intent = new Intent();
//                        intent.setAction(Intent.ACTION_VIEW);
//                        intent.addCategory(Intent.CATEGORY_DEFAULT);
//                        //将功能Scheme以URI的方式传入data
//                        Uri uri = Uri.parse("qqmap://map/routeplan?type=drive&to=" + address + "&tocoord=" + latitude + "," + longitude);
//                        intent.setData(uri);
//                        startActivity(intent);

                        String uriString1 = null;
                        StringBuilder builder1 = new StringBuilder("qqmap://map/routeplan?type=drive&policy=0&referer=zhongshuo");

                        builder1.append("&to=").append(address)
                                .append("&tocoord=").append(latitude)
                                .append(",")
                                .append(longitude);
                        uriString = builder1.toString();
                        intent = new Intent(Intent.ACTION_VIEW);
                        intent.setPackage("com.tencent.map");
                        intent.setData(Uri.parse(uriString));
                        startActivity(intent);

                        break;

                }
            }
        });
        bottomDialog.show();

    }

    private List<String> getMapApk() {
        List<String> itemList = new ArrayList<>();
        List<String> apkList = getApkList(this);
        if (apkList.contains("com.autonavi.minimap")) {

            itemList.add("高德地图");
        }
        if (apkList.contains("com.baidu.BaiduMap")) {
            itemList.add("百度地图");
        }
        if (apkList.contains("com.tencent.map")) {

            itemList.add("腾讯地图");
        }

        return itemList;
    }

    public List<String> getApkList(Context context) { //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        return packageNames;
    }

    public void back(View v) {
        finish();
    }

    //dip和px转换
    private static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    private void getAddressByLatLng(LatLng latLng) { //逆地理编码查询条件：逆地理编码查询的地理坐标点、查询范围、坐标类型。
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500f, GeocodeSearch.AMAP); //异步查询
        geocodeSearch.getFromLocationAsyn(query);
    }

    @Override
    public void onMyLocationChange(Location location) {
        Log.d(TAG, "onMyLocationChange: 定位成功了");


    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
        simpleAddress = regeocodeAddress.getFormatAddress();
        tv_address.setText(simpleAddress);

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}
